<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>配货管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<style type="text/css">
		.tmdyTable td{border:1px solid #00000080;} 
		.laytable-cell-1-imageUrl{
			height:100%;
			max-width:100%;
		}
	</style>
</head>
<script type="text/javascript">
	$(document).on('keydown','[lay-id="productAddTable"] .layui-table-edit',function(e){
		var td = $(this).parent('td'),
		tr = td.parent('tr'),
		trs = tr.parent().parent().find('tr'),
		tr_index = tr.index(),
		td_index = td.index(),
		td_last_index = tr.find('[data-edit="text"]:last').index(),
		td_first_index = tr.find('[data-edit="text"]:first').index();
		switch(e.keyCode){
			case 13:
			case 39:
				td.nextAll('[data-edit="text"]:first').click();
				if(td_index == td_last_index){
					tr.next().find('td').eq(td_first_index).click();
					if(tr_index == trs.length-1){
						trs.eq(0).find('td').eq(td_first_index).click();
					}
				}
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 37:
				td.prevAll('[data-edit="text"]:first').click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 38:
				tr.prev().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 40:
				tr.next().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
		} 
	})
</script>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>配货管理</cite>
        </a>
      </span>
</div>
<div class="x-body">
	<div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<!-- 获取配货单号 -->
						<input id="getDid" hidden="hidden">
						<input id="gys" hidden="hidden">
						<input id="getIndex" hidden="hidden">
						<input class="layui-input" name="keyword01" id="keyword01" placeholder="请输入配货单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<td>
						<!-- <input class="layui-input" name="sendCompany" id="sendCompanyc" placeholder="请输入供应商" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> -->
						<!-- <div style="width: 190px; float: left;"> -->
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="sendCompanyc" name="sendCompany">
								<!-- <select id="customer_id" name="customer_id" lay-verify="customer_id" lay-filter="customer_id" style="width: 190px"> -->
								<option value="">请选择供应商</option>
								<c:forEach items="${customer_type0}" var="customer">
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>
							</select>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload1"><i class="layui-icon layui-icon-search"></i>检索</button>
	</div>
	<xblock>
		<button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
		<button class="layui-btn layui-btn-danger" id="dels"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
		<button class="layui-btn layui-btn-danger" id="confirmPrepare"><i class="layui-icon layui-icon-delete"></i>确认配货</button>
		<!-- <button class="layui-btn layui-btn-danger" id="dels"><i class="layui-icon layui-icon-delete"></i>批量取消</button>
		<button class="layui-btn layui-btn-danger" id="restors"><i class="layui-icon layui-icon-delete"></i>批量恢复</button>
		<button class="layui-btn layui-btn-danger" id="dybd"><i class="layui-icon layui-icon-upload-drag"></i>打印表单</button>
		<button class="layui-btn layui-btn-danger" id="dybq"><i class="layui-icon layui-icon-upload-drag"></i>打印标签</button> -->
	</xblock>
	<table class="layui-hide" id="tableList" lay-filter="tableList"></table>
</div>
<div id="subDiv" hidden="hidden"  class="x-body">
	<xblock>
		<button class="layui-btn layui-btn-warm" id="addProduct"><i class="layui-icon layui-icon-add-circle-fine"></i>新增物料</button>
		<button class="layui-btn layui-btn-danger" id="delete2"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	</xblock>
	<table class="layui-hide" id="tableDetails" lay-filter="tableDetails"></table>
</div>

<!-- <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a> -->
<script type="text/html" id="rowToolbar">
	{{#  if(d.state ==0){ }}
		<a class="layui-btn layui-btn-xs" lay-event="confirmor"><i class="layui-icon layui-icon-edit"></i>确认</a>
    {{#  } }}
</script>

<script type="text/html" id="rowToolbar2">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete1"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script type="text/html" id="productAddRowToolbar">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="proDel">删除</a>
</script>

<!-- 导入框 -->
<div id="importDiv" hidden="hidden">
	<form class="layui-form" id="uploadform">
		<div style="margin: 20px 0 20px 140px;">
			<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
		</div>
	</form>
	<button class="layui-btn layui-btn-blue" lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
	<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
</div>
<!-- 产品选择框 -->
<div id="productDiv" hidden="hidden">
	<form class="layui-form">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- <td>
							<input class="layui-input" name="materiel_name" id="materiel_name" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> -->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_numm" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel" data-type="reloadm"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable" lay-filter="productTable"></table>
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
		</xblock>
	</form>
</div>

<!-- 二次产品选择框 -->
<div id="productDiv2" hidden="hidden">
	<form class="layui-form" id="addFormID2">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- 
						<td>
							<input class="layui-input" name="materiel_name" id="materiel_name2" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> 
						-->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_num2" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel2" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable2" lay-filter="productTable2"></table>
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform2" type="button" style="margin: 0px 0px 10px 216px; width: 400px">提交</button>
		</xblock>
	</form>
</div>

<!-- 新增框 -->
<div id="addDivID" hidden="hidden">
	<form class="layui-form" id="addFormID">
		<xblock>
			<table>
				<tr>
					<td><label class="layui-form-label">配货单号</label></td>
					<td>
						<input readonly class="layui-input" id="num" name="num" style="width: 160px; color: gray" placeholder="请输入配货单号">
						<input type="hidden" id="id" name="id">
					</td>
					<td>
						<label class="layui-form-label">供应商</label></td>
					<td>
						<div class="layui-input-inline" style="width:160px">
							<select class="layui-input" name="supplyid" id="supplyid" lay-filter="supplyid">
								<option value="" selected="selected">请选择供应商</option>
								<c:forEach items="${customer_type0}" var="customer" >
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>
							</select>
						</div>
						<div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
						<input type="hidden" id="text">
					</td>
					<td>
                        <label class="layui-form-label"></label>
                    </td>
					<td>
                        <button type="button" class="layui-btn layui-btn-normal" onclick="addProduct()">选择物料</button>
                    </td>
				</tr>
				<tr style="height:10px"></tr>
			</table>
		</xblock>
		<table id="productAddTable" lay-filter="productAddTable"></table>
		<xblock>
			<div align="center">
				<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm">提交</button>
				&emsp;&emsp;&emsp;&emsp;
				<button class="layui-btn layui-btn-primary">取消</button>
			</div>
		</xblock>
	</form>
</div>

<!-- 打印表单框 -->
<div id="dybdDivID" hidden="hidden">
	<div id="dyDiv" style="width: 100%;overflow-y:scroll;height: 549px">
		<table style="width: 100%;">
			<tr>
				<td align="center" rowspan="2">
					<img alt="" src="${pageContext.request.contextPath }/images/title.jpg">
				</td>
				<td align="center" colspan="2">
					<h1><span class="xt_title"></span></h1>
				</td>
			</tr>
			<tr>
				<td align="center" colspan="2">
					<h1>配货单</h1>
				</td>
			</tr>
			<tr style="height:3px"></tr>
			<tr>
				<td colspan="3" width="100%" align="center">
					<table width="70%">
						<tr>
							<td width="40%">
								送货单号：<span id="sendNumbers"></span>
							</td>
							<td width="30%">
								到货日期：
							</td>
							<td rowspan="7" width="30%">
								<img width="200px" id="bd_img"/>
							</td>
						</tr>
						<tr>
							<td>
								创建时间：<span id="createDate"></span>
							</td>
							<td>
								窗口时间：
							</td>
						</tr>
						<tr>
							<td>
								客户名称：<span id="sendNames"></span>
							</td>
							<td>
								到货地址：<span id="receiveAddress"></span>
							</td>
						</tr>
						<tr>
							<td>
								客户地址：<span id="sendAddress"></span>
							</td>
							<td>
								交货道口：
							</td>
						</tr>
						<tr>
							<td>
								发货联系人：<span id="sendPeoples"></span>
							</td>
							<td>
								配货联系人：<span id="receivePeoples"></span>
							</td>
						</tr>
						<tr>
							<td>
								联系电话：<span id="sendPhones"></span>
							</td>
							<td>
								联系电话：<span id="receivePhones"></span>
							</td>
						</tr>
						<tr>
							<td>
								备注：
							</td>
							<td>
								备注：
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="6"  width="100%" align="center">
					<table id="dytable" lay-filter="dytable">
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td align="center">
					发货人签字：
				</td>
				<td>
					承运商签字：
				</td>
				<td>
					配货人签字：
				</td>
			</tr>
			<tr>
				<td align="center">
					时间：
				</td>
				<td>
					时间：
				</td>
				<td>
					时间：
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					1. 发货时务必填全发货零件信息。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					2. 配货数量按实际数量核对签收。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					3. 单据一式三联，发货、配货、配货回单。
				</td>
			</tr>
		</table>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dayingTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<!-- 打印标签条码框 -->
<div id="dybqDivID" hidden="hidden">
	<div style="width: 100%;overflow-y:scroll;height: 499px">
		<table id="bqtable" lay-filter="bqtable">
		</table>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dytm" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<!-- 打印标签框 -->
<div id="dytmDivID" hidden="hidden">
	<div id="tmdyDiv" style="width: 100%;overflow-y:scroll;height: 499px">
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dayingTmdyTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<script type="text/javascript">
    var table;
    var customerId2;
    var receiveNumber2;
    layui.use(['table','layer','upload','form','laydate'], function(){
        table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;

        var $ = layui.jquery, active = {
            reload1:function () {
                var keyword01 = $.trim($("#keyword01").val());
                var sendCompany = $.trim($("#sendCompanyc").val());
                table.reload('contenttable',{
                    method:'get',
                    where:{
                    	num:keyword01
                        ,supplyid:sendCompany
                    }
                    ,page: {
                    	//重新从第 1 页开始
                        curr: 1
                    }
                });
            },
	        reload:function () {
	            var materiel_name2 = $.trim($("#materiel_name2").val());
	            var materiel_num2 = $.trim($("#materiel_num2").val());
	            var verify = /^[0-9,-]*$/;
	    		//if(verify.test(materiel_num2)){
	    			var split = materiel_num2.split(',')
	    			if(split.length <= 5){
	    				table.reload('andProcut2Id',{
							method:'post'
							,where:{"materielName":materiel_name2,"materielNum":materiel_num2}
			         		,page: {
			                    curr: 1//重新从第 1 页开始
			                }
						});
	    			}else{
	    				layer.msg("最多可同时查5个！");
	    			}
	    		/*} else{
	    			layer.msg("只能输入数字和英文逗号！");
	    		} */
	        },
	        reloadm:function () {
	            var materiel_name2 = $.trim($("#materiel_name2").val());
	            var materiel_num2 = $.trim($("#materiel_numm").val());
	            var verify = /^[0-9,-]*$/;
	    		//if(verify.test(materiel_num2)){
	    			var split = materiel_num2.split(',')
	    			if(split.length <= 5){
	    				table.reload('andProcut3Id',{
							method:'post'
							,where:{"materielNum":materiel_num2}
			         		,page: {
			                    curr: 1//重新从第 1 页开始
			                }
						});
	    			}else{
	    				layer.msg("最多可同时查5个！");
	    			}
	    		/*} else{
	    			layer.msg("只能输入数字和英文逗号！");
	    		} */
	        }
        }
        
      	//llm新增，添加物料的查询
        $(document).on('click','#selectMateriel',function(){
         	var materiel_name=$('#materiel_name').val();
     		var materiel_num=$('#materiel_num').val();
     		var table = layui.table;
     		var verify = /^[0-9,-]*$/;
    		//if(verify.test(materiel_num)){
    			var split = materiel_num.split(',')
    			if(split.length <= 5){
    				table.reload('productTable',{
						method:'post'
						,where:{"materielName":materiel_name,"materielNum":materiel_num}
		         		,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
    			}else{
    				layer.msg("最多可同时查5个！");
    			}
    		/*} else{
    			layer.msg("只能输入数字和英文逗号！");
    		} */
    	}) 
    	
      	//点击行checkbox选中
	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
	        var index = $(this).attr('data-index');
	        var tableBox = $(this).parents('.layui-table-box');
	        //存在固定列
	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
	        } else {
	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
	        }
	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
	        if (checkCell.length>0) {
	            checkCell.click();
	        }
	    });
	
	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
	        e.stopPropagation();
	    });
        
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        table.render({
            elem: '#tableList'
            ,url:'${pageContext.request.contextPath }/PrepareOne/list.do'
            ,title: 'machineList'
            ,id :'contenttable'
            ,limits:[10,20,30]
            ,toolbar: '#toolbar'
           	,request: {   //如果无需自定义请求参数，可不加该参数
                pageName: 'page' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            ,response: {   //如果无需自定义数据响应名称，可不加该参数
                countName: 'total' //规定数据总数的字段名称，默认：count
                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            ,cols: [
                [{type: 'checkbox',fixed: 'left'},
                    {field: 'id',title:'NO',sort: true,width: 50,type:'numbers',align:'center'},
                    {field: 'num',title: '配货单编号',align:'center'},
                    {field: 'supply',title: '供应商',align:'center',},
                    {field: 'person',title: '创建人',align:'center'},
                    {field: 'createTime',title: '创建时间',align:'center'},
                    {field: 'state',title: '状态',align:'center'
                        ,templet: function(d){
                            var value = d.state;
                            if(value == 0){
                                value = "未配货"
                            } else if (value == 1){
                                value = "已配货"
                            } else if (value == 2){
                                value = "配货中"
                            }
                            return value;
                        }
                    },
                ]
            ]
            ,page: true
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold'
                });
            }
        });

		
        /* 打印单据 */
        table.render({
            elem: '#dytable'
            //,url:'${pageContext.request.contextPath }/receiveDetail/list.do'
            ,title: '明细表'
            ,cols: [[
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'materiel_num', title:'QAD/SAP', align:'center', width: 150},
                 /* {field:'brevity_num', title:'供应商零件号', align:'center', width: 200}, */
                 {field:'materiel_name', title:'中文描述', align:'center', width: 250,},
                 {field:'unit', title:'单位', align:'center', width: 87},
                 {field:'packing_quantity', title:'单包装数', width: 100, align:'center'},
                 {field:'sendNum', title:'发货包装数', align:'center', width: 100},
                 {field:'totalNum', title:'发货件数', align:'center', width: 100},
                 {field:'receiveNum', title:'实收包装数', align:'center', width: 100},
                 {field:'codeNum', title:'实收件数', align:'center', width: 100},
                 {field:'pici', title:'批号/备注', align:'center', width: 150},
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        /* 打印标签 */
        table.render({
            elem: '#bqtable'
            ,title: '条码表'
            ,cols: [[
				 {type: 'checkbox',fixed: 'left'},
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'SAP_QAD', title:'SAP_QAD', align:'center', width: 150},
                 {field:'materiel_name', title:'中文名称', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.materiel_name
	                     }
	                     return value;
                 	}
                 },
                 /* {field:'brevity_num', title:'零件号', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.brevity_num
	                     }
	                     return value;
                 	}
                 }, */
                 {field:'packing_quantity', title:'包装数量', width: 100, align:'center'
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.packing_quantity
	                     }
	                     return value;
                 	}
                 },
                 {field:'pici', title:'批次', align:'center'
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.pici
	                     }
	                     return value;
                 	}
                 },
                 {field:'code', title:'条码', align:'center', width: 200},
                 {field:'num', title:'数量', align:'center', width: 150,},
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        
        /*=======================点击配货计划的下表=======================*/
        table.on('row(tableList)', function(obj){
        	var data = obj.data;
        	$("#getDid").val(data.id);
        	$("#gys").val(obj.data.supply);
        	$("#subDiv").show();
            customerId2 = data.supplyid;
            receiveNumber2 = data.num;
            table.render({
                elem: '#tableDetails'
                ,url:'${pageContext.request.contextPath }/PrepareDetail/list.do?did='+data.id
                ,toolbar: '#toolbar'
                ,title: '明细表'
                ,id :'contenttableDetails'
                ,limits:[10,20,30]
                //,defaultToolbar:['filter', 'print']
                ,request: {   //如果无需自定义请求参数，可不加该参数
	                pageName: 'page' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
	            }
	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
	                countName: 'total' //规定数据总数的字段名称，默认：count
	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
	            }
                ,cols: [[
                    {type: 'checkbox',fixed: 'left'},
                    {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                    {field:'mid', title:'物料id', align:'center', hide:true,},
                    /* {field:'sqd', title:'SAP/QAD', align:'center',event: 'collapse', width: 300,}, */
                    {field:'sqd', title:'SAP/QAD', align:'center', width: 300,
                    	event: 'collapse',
						templet: function(d) {
							return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.sqd + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
						}
                    },
                    {field:'materialName', title:'中文名称', align:'center',width: 400},
                    {field:'subnum', title:'提交数量', align:'center', width: 100},
                    {field:'plannum', title:'需要数量', align:'center', width: 100},
                    {field: 'state',title: '状态',align:'center', width: 80
                        ,templet: function(d){
                            var value = d.state;
                            if(value == 0){
                                value = "未配货"
                            } else if (value == 1){
                                value = "已配货"
                            } else if (value == 2){
                                value = "配货中"
                            }
                            return value;
                        }
                    },
                    {field:'location', title:'推荐库位', align:'center'
                        ,templet: function(d){
                            var value = "";
                            if (d.state != 1 && null != d.location){
                                value = d.location;
                            }
                            return value;
                        }
                    },
                ]]
                ,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
        });

        table.render({
            elem: '#productAddTable'
            ,defaultToolbar:['filter', 'print']
            ,cols: [[
                {type: 'checkbox',fixed: 'left'},
                {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                {field:'id', title:'id', align:'center', hide:true},
                {field:'mid', title:'mid', align:'center', hide:true},
                //{field:'customer_name', title:'供应商名称', align:'center',width:100},
                {field:'materiel_num', title:'SAP/QAD', align:'center'},
                {field:'materiel_name', title:'中文名称', align:'center', width:150},
                /* {field:'brevity_num', title:'零件号', align:'center'}, */
                //{field:'unit', title:'单位', align:'center',width:60},
                {field:'packing_quantity', title:'包装数量', align:'center', width: 90},
                /* {field:'container_name', title:'容器名称', align:'center'},
                {field:'is_devanning', title:'是否拆箱', align:'center',width:80
                    ,templet: function(d){
                        var value = d.is_devanning;
                        if(value == '0'){
                            return "是";
                        } else if (value == '1') {
                            return "否";
                        }
                    }
                }, 
                {field:'devanning_num', title:'拆箱数', align:'center',width:70},
                {field:'outgoing_frequency', title:'出库频率', align:'center', width: 90},
                {
                    field: 'barcode_type',
                    title: '条码类型',
                    align:'center',
                    width: 90
                    ,templet: function(d){
                        var value = d.barcode_type;
                        if(value == 0){
                            return "精准码";
                        } else if (value == 1) {
                            return "产品码";
                        } else {
                            return "简码";
                        }
                    }
                },*/
                {field:'plannum', title:'<span style="color: red">配货数量</span>', edit: 'text', align:'center', width: 110},
            ]]
            ,limit:Number.MAX_VALUE
            ,page: false
            ,height: 400
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });

        //监听行工具事件
        table.on('tool(productAddTable)', function(obj){
            var data = obj.data;
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            //单个删除
            if(obj.event === 'delete1'){
                layer.confirm('确定删除吗？', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                });
            }
        });
        
        //监听配货计划管理的编辑事件
        table.on('tool(tableList)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                if(data.state != 0){
                    toastr.warning("对不起，已配货的数据不能修改！");
                    return;
                }
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1100px', '640px'] 	//宽  高
                    ,title: '编辑'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                        $("#id").val(data.id)
                        $("#num").val(data.num)
                        $("#supplyid").val(data.supplyid)
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'did='+data.id,
                            url:'${pageContext.request.contextPath}/PrepareDetail/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                newData = data;
                            }
                        });
                        table.reload('productAddTable',{
                            data : newData
                        });
                        form.render();
                    }
                });
            } else if (obj.event === 'confirmor'){
            	var num = 0;
                $.ajax({
                    type:'post',
                    data:'did='+data.id,
                    url:'${pageContext.request.contextPath}/PrepareDetail/queryAllByMution.do',
                    dataType: 'JSON',
                    async: false,
                    success:function (data) {
                    	for (var i = 0; i < data.length; i++) {
	                    	num = num + data[i].subnum;
						}
                    }
                });
                //alert(num)
                if(num > 0){
	            	$.ajax({
	                    type:'post',
	                    data:'id='+data.id+"&state=1",
	                    url:'${pageContext.request.contextPath}/PrepareOne/update.do',
	                    dataType: 'JSON',
	                    async: false,
	                    success:function (data) {
	                        if(data > 0){
	                        	toastr.success('操作成功');
	                        }else{
	                        	toastr.error('操作失败');
	                        }
	                        setTimeout(function(){
	                            window.location.reload();
	                        },1000);
	                    }
	                });
                }else{
                	toastr.warning("对不起，配货数量为0的数据不能确认配货！");
                	return;
                }
            }
        });

        //监听配货计划管理详细表的父子表事件
        table.on('tool(tableDetails)', function(obj){
			if (obj.event === 'collapse') {
				var trObj = layui.$(this).parent('tr'); //当前行
				var accordion = true //开启手风琴，那么在进行折叠操作时，始终只会展现当前展开的表格。
				var content = '<table></table>' //内容
				//表格行折叠方法
				collapseTable({
					elem: trObj,
					accordion: accordion,
					content: content,
					success: function (trObjChildren, index) { //成功回调函数
						//trObjChildren 展开tr层DOM
						//index 当前层索引
						trObjChildren.find('table').attr("id", index);
                        /*===================================start===================================*/
						table.render({
							elem: "#" + index
                            ,url:'${pageContext.request.contextPath }/PrepareDetailCode/list.do?ddid=' + obj.data.id
                            ,title: 'machineList'
                            ,limits:[10,20,30]
                           	,request: {   //如果无需自定义请求参数，可不加该参数
               	                pageName: 'page' //页码的参数名称，默认：page
               	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
               	            }
               	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
               	                countName: 'total' //规定数据总数的字段名称，默认：count
               	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
               	            }
                            ,cols:
								[[
                                    {field:'id', title:'序号', sort: true, width: 60, type:'numbers', align:'center'},
                                    {field:'codeMark', title: '条码', align:'center'},
                                    {field:'preNum', title: '配货数量', align:'center'},
                                    //{field:'location_name', title: '库位名称', align:'center'},
                                    //{field:'location_num', title: '库位编号', align:'center'},
                                    {field:'preMan', title: '配货人', align:'center'},
                                    {field:'preTime', title: '配货时间', align:'center'},
                                ]]
                            ,page: true
                            ,done : function(){
                                $('th').css({
                                    'background-color': '#009688', 'color': '#fff','font-weight':'bold'
                                })
                            }
						});
						/*===================================end===================================*/
					}
				});
			}
        });

        //选择供应商选中id查询该供应商的所有物料
        form.on('select(supplyid)', function(data){
            var customer_id = data.value;
            $.ajax({
                type:'post',
                data:'id='+customer_id,
                url:'${pageContext.request.contextPath}/others/customerByName.do',
                dataType: 'JSON',
                async: false,
                success:function (json) {
                    if(null != json){
                        $("#sendName").val(json.contacts_name)
                    }
                }
            });
            table.reload('productAddTable',{
                data : new Array()
            });
        });

        /**
         * 添加弹框中，选择物料后，点提交，带回的操作
         */
        form.on('submit(productform)', function (data) {
            var flag;
            var oldData = table.cache["productAddTable"];
            var checkStatus = table.checkStatus('andProcut3Id')
            //选中的物料
            var data = checkStatus.data;
            console.log(data);
            for (var j = 0; j < data.length; j++) {
                for (var k = 0; k < oldData.length; k++) {
                    if (oldData[k].id == data[j].id) {
                        flag = 0;
                    }
                }
            }
            if (flag != 0) {
                for (var i = 0; i < data.length; i++) {
                    oldData.push(data[i]);
                }
            } else {
                toastr.warning("记录已经存在，不能重复添加");
            }
            table.reload('productAddTable',{
                data : oldData
            });
            $('[lay-id="productAddTable"] [data-edit="text"]:first').click();
            layer.close(productIndex)
            return false;
        });

        /**
         * 新增--提交
         */
        form.on('submit(addForm)', function (data) {
            var did = $("#id").val();
            //获取明细中数据
            var oldData = table.cache["productAddTable"];
            var data = oldData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                return !re.test(item.plannum) || item.plannum == "";
            })
            if(oldData.length == 0){
                toastrStyle();
                toastr.warning("请添加物料详情！");
                return false;
            } else if (data.length > 0){
                toastrStyle();
                toastr.warning("请输入正确的配货量(大于0的正整数)");
            	return false;
            } else {
            	var mids = new Array()
            	var plannums = new Array()
            	//获取明细表中的所有记录，遍历，循环添加
                for (var i = 0; i < oldData.length; i++) {
                    mids.push(oldData[i].id);
                    plannums.push(oldData[i].plannum);
                }
            	var title = "新增";
                var url = '${pageContext.request.contextPath}/PrepareOne/insert.do';
                var id = $.trim($("#id").val());
                if(id != "" && id != null && id != 'undefined'){
                    var url = '${pageContext.request.contextPath}/PrepareOne/update.do';
                    title = "修改";
                }
                var fromdata = $("#addFormID").serialize()+"&mids="+mids+"&plannums="+plannums;
                //添加配货单
                $.ajax({
                    url : url,
                    data: fromdata,
                    cache : false,
                    async: false,
                    type : "post",
                }).done(
                    function(res) {
                        if (res > 0) {
                            toastr.success(title+'成功');
                            /* setTimeout(function(){
                                window.location.reload();
                                $("#reset").click();
                            },1000); */
                            layer.closeAll();
                            table.reload('contenttable',{
                                method:'get',
            	                page: {
            	                    curr: 1//重新从第 1 页开始
            	                }
                            });
                        }else if(res == -1){
                        	toastr.success("配货单编号重复"+title+'失败');
                            /* setTimeout(function(){
                                window.location.reload();
                                $("#reset").click();
                            },1000); */
                        	layer.closeAll();
                            table.reload('contenttable',{
                                method:'get',
            	                page: {
            	                    curr: 1//重新从第 1 页开始
            	                }
                            });
                        }else{
                            toastr.error(title+'失败！');
                            /* setTimeout(function(){
                                location.reload();
                            },1000); */
                            layer.closeAll();
                            table.reload('contenttable',{
                                method:'get',
            	                page: {
            	                    curr: 1//重新从第 1 页开始
            	                }
                            });
                        }
                    }
                ).fail(
                    function(res) {
                        toastr.error(title+'失败！');
                        /* setTimeout(function(){
                            location.reload();
                        },1000); */
                        layer.closeAll();
                        table.reload('contenttable',{
                            method:'get',
        	                page: {
        	                    curr: 1//重新从第 1 页开始
        	                }
                        });
                    }
                )
                return false;
            }
        });

        /**
         * 下表添加物料提交
         */
        form.on('submit(productform2)', function (data) {
        	//获取配货单号
        	var did = $("#getDid").val();
        	//获取该表格中选中的数据
        	var checkStatus = table.checkStatus('andProcut2Id')
        	var checkData = checkStatus.data;
        	//获取明细中数据
            //var oldData = table.cache["andProcut2Id"];
        	//alert(checkData.length);
            var data = checkData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                return !re.test(item.plannum) || item.plannum == "";
            })
            if(checkData.length == 0){
                toastrStyle();
                toastr.warning("请添加物料详情！");
                return false;
            } else if (data.length > 0){
                toastrStyle();
                toastr.warning("请输入正确的配货量(大于0的正整数)");
            	return false;
            }else {
	        	for (var i = 0; i < checkData.length; i++) {
	        		//checkData[i].id指的是物料id
					var mid = checkData[i].id;
					var plannum = checkData[i].plannum;
		            //添加配货明细
		            $.ajax({
		                url: '${pageContext.request.contextPath}/PrepareDetail/insert.do' ,
		                type: 'post',
		                data: {mid:mid, plannum:plannum, did:did},
		                async: false,
		                dataType:'JSON',
		                success: function (result) {
		                    if (result > 0) {
		                    	toastr.success("新增成功！");
		                    	/* setTimeout(function(){
	                                window.location.reload();
	                            },1000); */
		                    	layer.closeAll();
                                table.reload('contenttableDetails',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
		                    } else if (result == -1) {
		                    	toastr.warning("该物料已存在，请选择其他物料");
		                    	/* setTimeout(function(){
	                                window.location.reload();
	                            },1000); */
		                    } else {
		                        toastr.warning("对不起，明细添加失败！");
		                    }
		                },
		                error: function (data) {
		                    toastr.error("对不起，明细添加错误！");
		                }
		            })
				}
            }
        });
        
      	/* ======配货单的批次行内编辑====== */
        /* table.on('edit(productAddTable)', function(obj){
            var fieldValue = obj.value, 	//得到修改后的值
            rowData = obj.data.pici, 		//得到所在行所有键值
            fieldName = obj.field; 			//得到字段
            //保存修改出库单详细表的值    
            alert(rowData);
            layui.use('jquery',function() {
                var $ = layui.$;
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath}/stockOutOrder/updateOutStockOrderDetailById.do",
                    data: {id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                    success: function(zcInventoryInfoId){
                        if(zcInventoryInfoId > 0) {
                            toastrStyle();
                            toastr.success("修改成功！");
                        }else{
                            toastrStyle();
                            toastr.warning("修改失败！");
                        }
                    }
                });
            });
        }); */
      	/* ============ */
        //增加
        $("#add").click(function(){
            layer.open({
                type: 1 					//Page层类型
                ,area: ['1100px', ''] 		//宽  高
                ,title: '新增'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,end: function () {
                    var formDiv = document.getElementById('addDivID');
                    formDiv.style.display = '';
                    $("#supplyid").val("");
                }
                ,success: function(){
                    var timestamp = (new Date()).getTime();
                    $("#num").val("P-"+timestamp);
                    table.reload('productAddTable',{
                        data : new Array()
                    });
                    $("#supplyid").val("")
                    form.render();
                }
            });
        });
        
        //llm 监听行内编辑
        table.on('edit(productAddTable)', function(obj){
        	//设置jQuery对象
        	LayUIDataTable.SetJqueryObj($);
        	//隐藏列-单列模式
            LayUIDataTable.HideField('num');
         	//隐藏列-多列模式
            LayUIDataTable.HideField(['num','match_guest']);
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            	$("#getIndex").val(index);
            })
            /* ========================== */
        	var fieldValue = obj.value, //改变后的值
	    	 	rowData = obj.data, 	//得到所在行所有键值
             	fieldName = obj.field; 	//得到字段
           	var sum = 0;
          	//如果发货数量有值
            if(rowData.sendNum.length != 0){
            	//如果单个数量也有值
           		if(rowData.singleNum.length != 0){
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity) + parseInt(rowData.singleNum))
           		} else {
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity));
           		}
           	}
            var opt = rowData.receiveNum;
            opt = sum;
            var allTr = $("#addFormID").find(".layui-table tbody").eq(0).find("tr");
           	for(var i = 0; i < allTr.length; i++){
				if($("#getIndex").val() == i){
					allTr.eq(i).children("td").eq(11).children('div').html(opt);
           		}
          	}
        });
	    	
        /* //监听下表新增物料的行内编辑事件
        table.on('edit(productTable2)', function(obj){
        	//设置jQuery对象
        	LayUIDataTable.SetJqueryObj($);
        	//隐藏列-单列模式
            LayUIDataTable.HideField('num');
         	//隐藏列-多列模式
            LayUIDataTable.HideField(['num','match_guest']);
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            	$("#getIndex").val(index);
            })
        	var fieldValue = obj.value, //改变后的值
	    	 	rowData = obj.data, 	//得到所在行所有键值
             	fieldName = obj.field; 	//得到字段
           	var sum = 0;
            //如果发货数量有值
            if(rowData.sendNum.length != 0){
            	//如果单个数量也有值
           		if(rowData.singleNum.length != 0){
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity) + parseInt(rowData.singleNum))
           		} else {
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity));
           		}
           	}
            var opt = rowData.receiveNum;
            opt = sum;
            var allTr = $("#addFormID2").find(".layui-table-main tbody").eq(0).find("tr");
          	for(var i = 0; i < allTr.length; i++){
				if($("#getIndex").val() == i){
					allTr.eq(i).children("td").eq(10).children('div').html(opt);
          		}
         	}
        }); */
        
        //配货计划单批量删除
        $("#dels").click(function() {
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            }else{
                var ids = "";
                for(var i=0;i<data.length;i++){
                    if(data[i].state != 0){
                        toastr.warning("对不起，已配货的数据不能删除！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    }else{
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定删除吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/PrepareOne/delete.do',
                        data:{"ids":ids},
                        success:function(data){
                            if(data > 0){
                                toastr.success("删除成功！");
                                /* setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                    //关闭模态框
                                    //父页面刷新
                                    window.location.reload();
                                },2000); */
                                table.reload('contenttable',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
                            } else {
                                toastr.warning("删除失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        });
        //配货计划单批量删除
        $("#confirmPrepare").click(function() {
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length != 1 || data[0].state == 1){
                toastr.warning("请选择一条未配货完成记录！");
            }else{
                layer.confirm('确定确认吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/PrepareOne/updateState.do',
                        data:{"id":data[0].id,"state":1},
                        success:function(data){
                            if(data > 0){
                                toastr.success("确认成功！");
                                table.reload('contenttable',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
                            } else {
                                toastr.warning("确认失败！");
                                table.reload('contenttable',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        });
        
        //llm 配货单详情添加物料
        $("#addProduct").click(function() {
        	var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
        	var str = "";
        	if(data.length == 0){
                toastr.warning("请选择一条记录！");
            } else if(data.length > 1){
            	toastr.warning("只能选择一条记录！");
            }else{
            	for(var i = 0; i < data.length; i++){
            		if(data[i].state != "0"){
            			toastr.warning("对不起，已配货的数据不能添加物料！");
            			return;
            		}
            	}
            	layer.open({
            		type: 1 					//Page层类型
                    ,area: ['900px', '700px'] 	//宽  高
                    ,title: '物料清单'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#productDiv2')
                    ,end: function () {
                        var formDiv = document.getElementById('productDiv2');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                    	table.render({
                            elem: '#productTable2'
                            ,id:'andProcut2Id'
                            //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?id='+customer_id
                            //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
                            ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customerId2+'&source=1'
                            ,limits:[10,20,30]
                            ,defaultToolbar:['filter', 'print']
                            ,request: {
                                pageName: 'page' 	//页码的参数名称，默认：page
                                ,limitName: 'limit' //每页数据量的参数名，默认：limit
                            }
                            ,cols: [
                                [{
                                    type: 'checkbox',
                                    fixed: 'left'
                                }, {
                                    field:'id2',
                                    title:'序号',
                                    sort: true,
                                    width: 60,
                                    type:'numbers',
                                    align:'center'
                                }, {
                                    field: 'id',
                                    title: 'id',
                                    hide: true
                                } , {
                                    field: 'materiel_num',
                                    title: 'SAP/QAD',
                                    align:'center',
                                /* }, {
    	                            field: 'brevity_num',
    	                            title: '零件号',
    	                            align:'center', */
                            	}, {
                                    field: 'materiel_name',
                                    title: '中文名称',
                                    align:'center',
                                }, {
                                    field: 'packing_quantity',
                                    title: '包装数量',
                                    align:'center',
                                }, {
                                    field: 'num',
                                    title: '库存数量',
                                    align:'center',
                                }, {
                                    field: 'plannum',
                                    //title: '发货数量（箱）',
                                    title: '配货数量',
                                    align:'center',
                                    edit:true,
                                }]
                            ]
                            ,page: true
                        });
                    	
                    	/* **********键盘Enter事件*********** */ 
                        $(document).keydown(function (event) {
                            if (event.keyCode == 13) { //绑定回车 
                            	var materiel_name2 = $.trim($("#materiel_name2").val());
                	            var materiel_num2 = $.trim($("#materiel_num2").val());
                	            var verify = /^[0-9,-]*$/;
                	    		//if(verify.test(materiel_num2)){
                	    			var split = materiel_num2.split(',')
                	    			if(split.length <= 5){
                	    				table.reload('andProcut2Id',{
                							method:'post'
                							,where:{"materielName":materiel_name2,"materielNum":materiel_num2}
                			         		,page: {
                			                    curr: 1//重新从第 1 页开始
                			                }
                						});
                	    			}else{
                	    				layer.msg("最多可同时查5个！");
                	    			}
                	    		/*} else{
                	    			layer.msg("只能输入数字和英文逗号！");
                	    		} */
                	    		return false;
                	        }
                        });
                      	/* **********Enter事件*********** */
                    }
            	});
            }
        });
        
      	//配货计划单详细批量删除
        $("#delete2").click(function() {
            var checkStatus = table.checkStatus('contenttableDetails')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            } else {
                var ids = "";
                for(var i = 0; i < data.length; i++) {
                    if(data[i].state != 0){
                        toastr.warning("对不起，已配货的数据不能删除！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    } else {
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定删除吗？', function(index){
                    $.ajax({
                        type : 'post',
                        url : '${pageContext.request.contextPath }/PrepareDetail/delete.do',
                        data : {"ids":ids},
                        success : function(data){
                            if(data > 0) {
                                toastr.success("删除成功！");
                                /* setTimeout(function(){  
                                    window.location.reload();
                                },2000); */
                                table.reload('contenttableDetails',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
                            } else {
                                toastr.warning("删除失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        });
        
      	//打印表单
        $("#dybd").click(function(){
        	var checkStatus = table.checkStatus('contenttable')
            var datas = checkStatus.data;
            if(datas.length!=1){
                toastr.warning("请选择一条记录！");
            }else{
            	var data = datas[0]
	            layer.open({
	                type: 1 					//Page层类型
	                ,area: ['1450px', '650px'] 			//宽  高
	                ,title: '打印表单'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: $('#dybdDivID')
	                ,end: function () {
	                    var formDiv = document.getElementById('dybdDivID');
	                    formDiv.style.display = '';
	                }
	                ,success: function(){
	                	//alert(data.sendPhone + "== "+ data.sendAdress);
                        $("#sendNumbers").html(data.sendNumber);
                        $("#createDate").html(data.sendDate);
                        $("#sendNames").html(data.sendCompany);
                        $("#sendPeoples").html(data.sendName);
                        $("#sendPhones").html(data.sendPhone);
                        //$("#receiveNames").html(data.receiveName);
                        $("#sendAddress").html(data.sendAdress);
                        //二维码路径
                        var path = '${pageContext.request.contextPath}/'
                        $.ajax({
                            type:'post',
                            data:'code='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/label/erWeiMa.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                            	path = path+data.path;
                            }
                        });
                        $("#bd_img").attr("src",path)
                        
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveNumber='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/receiveDetail/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                console.log(data);
                            	newData = data;
                            }
                        });
                        table.reload('dytable',{
                            data : newData
                            ,limit:newData.length
                        });
	                }
	            });
            }
        });
      	
        $("#dayingTable").click(function(){
			//var innerHTML = document.getElementById("dyDiv").innerHTML;
        	//printpage(innerHTML)
		    var obj =document.getElementById('dyDiv')
			var css='<style>'
                //+"#dyTable td{border:1px solid #00000080;}"
                +'[lay-id="dytable"] table{border:1px solid #F00;border-collapse:collapse;}'
                +'[lay-id="dytable"] table td{border:1px solid #222;}'
                +'[lay-id="dytable"] table th{border:1px solid #222;font-size: 20px;}'
                +'[lay-id="dytable"] table th span{color: black;}'
                +'</style>'; 
			var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
			var docStr =  css+ obj.innerHTML;
		    newWindow.document.write(docStr);
		    newWindow.document.close();
		    setTimeout(function () {
			    newWindow.print();
			    newWindow.close();
		    }, 100);
		});
      	//打印标签
        $("#dybq").click(function(){
        	var checkStatus = table.checkStatus('contenttable')
            var datas = checkStatus.data;
            if(datas.length!=1){
                toastr.warning("请选择一条记录！");
            }else{
            	var data = datas[0]
	            layer.open({
	                type: 1 					//Page层类型
	                ,area: ['1210px', '600px'] 			//宽  高
	                ,title: '条码列表'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: $('#dybqDivID')
	                ,end: function () {
	                    var formDiv = document.getElementById('dybqDivID');
	                    formDiv.style.display = '';
	                }
	                ,success: function(){
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveId='+data.id,
                            url:'${pageContext.request.contextPath}/receiveDetail/selectReceiveMarkByReceiveId.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                console.log(data);
                            	newData = data.data;
                            }
                        });
                        table.reload('bqtable',{
                            data : newData
                            ,limit:newData.length
                        });
	                }
	            });
            }
        });
      	//打印标签
        $("#dytm").click(function(){
        	var checkStatus = table.checkStatus('bqtable')
            var datas = checkStatus.data;
            if(datas.length < 1){
                toastr.warning("请选择条码！");
            }else{
            	layer.closeAll();
            	var num = datas.length;
           	  	var hight = '600px'
           	  	/* if(num > 2){
            	  	hight = '90%'
           	  	} */
           	  	var data = datas[0]
   	            layer.open({
   	                type: 1 					//Page层类型
   	                ,area: ['1200px', hight] 			//宽  高
   	                ,title: '打印标签'
   	                ,shade: 0.6 				//遮罩透明度
   	                ,maxmin: true 				//允许全屏最小化
   	                ,anim: 1 					//0-6的动画形式，-1不开启
   	                ,content: $('#dytmDivID')
   	                ,end: function () {
   	                    var formDiv = document.getElementById('dytmDivID');
   	                    formDiv.style.display = '';
   	                }
   	                ,success: function(){
   	                	var checkStatus = table.checkStatus('contenttable')
   	                 	var datas1 = checkStatus.data;
   	                	var customer_name = datas1[0].sendCompany;
   	                	
   	                	var time = curentTime();
   	                	var tmwmimg = '<%=request.getContextPath()%>/';
   	                	var materiel_name = "";
   	                	var materiel_num = "";
   	                	var packing_quantity = "";
   	                	var pici = "";
   	                	var tm = "";
   	                	var tmnum = 0;
   	                	var tm2wmimg = "";
   	                	var tm1wmimg = "";
   	                	var code = datas;
  	                	var html = '';
   	                	for (var i = 0; i < num; i++) {
   	                		/* tm = code[i][0];
                            tm2wmimg = tmwmimg+code[i][1];
                            tm1wmimg = tmwmimg+code[i][2]; */
                            var receiveDetail = code[i].receiveDetail
                            materiel_name = receiveDetail.materiel_name;
       	                	materiel_num = receiveDetail.materiel_num;
       	                	packing_quantity = receiveDetail.packing_quantity;
       	                	pici = receiveDetail.pici;
       	                	
   	                		tm = code[i].code;
                            tmnum = code[i].num;
                            tm2wmimg = tmwmimg+code[i].twoCodePath;
                            tm1wmimg = tmwmimg+code[i].barCodePath;
   	                		html += '<table class="tmdyTable" style="border: 2px solid #222;width: 540px;height: 260px;margin:0 auto;margin-bottom: 80px;float:left;margin-left: 48px;">'
   	                			html += '<tr>'
   	                				html += '<td width="100" align="center">'
   	                					html += '零件名称：'
   	                				html += '</td>'
   	                				html += '<td width="220">'
   	                				html += materiel_name
   	                				html += '</td>'
   	                				html += '<td rowspan="8" width="200">'
   	                					html += '<img src="'+tm2wmimg+'" width="100%" height="100%"/>'
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += 'SAP/QAD：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += materiel_num
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '供应商：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += customer_name
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '包装信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += packing_quantity
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '包装数量：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += tmnum
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '日期时间：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += time
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '批次信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += pici
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '条码信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += tm
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td colspan="3">'
   	                					html += '<img src="'+tm1wmimg+'" width="100%" height="50px" id="dpddremark_dy"/>'
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr style="height:5px"></tr>'
   	                		html += '</table>'
						}
   	                	var tmdyDiv = document.getElementById("tmdyDiv");
  	                		tmdyDiv.innerHTML= html;
   	                }
   	            });
            }
        });
        $("#dayingTmdyTable").click(function(){
        	//layer.closeAll();
		    var obj =document.getElementById('tmdyDiv')
			var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
			var css='<style>'
                +".tmdyTable td{border:1px solid #00000080;}"
                +'.tmdyTable{border:1px solid #F00;border-collapse:collapse;}'
                +'.tmdyTable td{border:1px solid #222;}'
                +'</style>'; 
			var docStr =  css+ obj.innerHTML;
			newWindow.document.write(docStr);
		    newWindow.document.close();
		    newWindow.print();
		    //newWindow.close(); 
            /* cc =  docStr;
	        var isIe=0;
	        if(navigator.userAgent.indexOf('MSIE')>0){
	          isIe = 1;
	        }
	        var frame = document.getElementById('dsh_myframe');
	        if (!frame) {
	          if (isIe) {
	            frame = document.createElement('<iframe id = "dsh_myframe"></iframe>');
	          } else {
	            frame = document.createElement('iframe');
	            frame.id ='dsh_myframe';
	            frame.setAttribute('style','width: 0pt; height: 0pt;')
	          }
	        }
	        if (isIe) {
	          frame.src = 'javascript:;';
	          frame.style.cssText= 'width: 0pt; height: 0pt;';
	        }
	        document.body.appendChild(frame);
	        if (isIe) {
	          doc = frame.contentWindow.document;
	        } else {
	          doc = frame.contentDocument;
	        }
	        doc.write(cc);
	        doc.close();
	        frame.contentWindow.focus();
	        if(isIe){
	          setTimeout(function(){
	            frame.contentWindow.print();
	          },2);
	        }else{
	          frame.contentWindow.print();
	        }  */
	        
		});
		//表格行折叠方法
        function collapseTable(options) {
            var trObj = options.elem;
            if (!trObj) {
                return;
            }
            var accordion = options.accordion,
                success = options.success,
                content = options.content || '';
            var tableView = trObj.parents('.layui-table-view'); //当前表格视图
            var id = tableView.attr('lay-id'); //当前表格标识
            var index = trObj.data('index'); //当前行索引
            var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
            var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
            var colspan = trObj.find('td').length; //获取合并长度
            var trObjChildren = trObj.next(); //展开行Dom
            var indexChildren = id + '-' + index + '-children'; //展开行索引
            var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
            var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
            var lw = leftTr.width() + 15; //左宽
            var rw = rightTr.width() + 15; //右宽
            //不存在就创建展开行
            if (trObjChildren.data('index') != indexChildren) {
                //装载HTML元素
                var tr = '<tr data-index="' + indexChildren + '"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
                trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
                var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
                leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
                rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
            }
            //展开|折叠箭头图标
            trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
            //显示|隐藏展开行
            trObjChildren.toggle();
            //开启手风琴折叠和折叠箭头
            if (accordion) {
                trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
                trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
                rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
                leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
            }
            success(trObjChildren, indexChildren); //回调函数
            heightChildren = trObjChildren.height(); //展开高度固定
            rightTrChildren.height(heightChildren + 115).toggle(); //左固定
            leftTrChildren.height(heightChildren + 115).toggle(); //右固定
        }
    });

    /*================点击选择物料的弹框================*/
    function addProduct (){
        if ($("#supplyid").val() == "" || $("#supplyid").val() == null || $("#supplyid").val() == 0) {
            //toastr.warning("请选择供应商！");
            layer.msg("请选择供应商！");
		}else if($("#num").val().trim() == ""){
			layer.msg("请输入配货单号！");
		} else {
            productIndex = layer.open({
                type: 1 					//Page层类型
                ,area: ['900px', '700px'] 	//宽  高
                ,title: '物料清单'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#productDiv')
                ,end: function () {
                    var formDiv = document.getElementById('productDiv');
                    formDiv.style.display = '';
                }
                ,success: function () {
                    var customer_id = $("#supplyid").val();
                    table.render({
                        elem: '#productTable'
                        //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?id='+customer_id
                        //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
                        ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customer_id+'&source=1'
                        ,limits:[10,20,30]
                        ,id:'andProcut3Id'
                        ,defaultToolbar:['filter', 'print']
                        ,request: {   //如果无需自定义请求参数，可不加该参数
                            pageName: 'page' //页码的参数名称，默认：page
                            ,limitName: 'limit' //每页数据量的参数名，默认：limit
                        }
                        ,cols: [
                            [{
                                type: 'checkbox',
                                fixed: 'left'
                            }, {
                                field:'id',
                                title:'序号',
                                sort: true,
                                width: 60,
                                type:'numbers',
                                align:'center'
                            }, {
                                field: 'id',
                                title: 'id',
                                hide:true
                            } /* , {
                                field: 'customer_name',
                                title: '供应商名称',
                                align:'center',
                            } */, {
                                field: 'materiel_num',
                                title: 'SAP/QAD',
                                align:'center',
                            /* }, {
	                            field: 'brevity_num',
	                            title: '零件号',
	                            align:'center', */
                        	}, {
                                field: 'materiel_name',
                                title: '中文名称',
                                align:'center',
                            }, /* {
                                field: 'outgoing_frequency',
                                title: '出库频率',
                                align:'center',
                            }, */ {
                                field: 'packing_quantity',
                                title: '包装数量',
                                align:'center',
                            }, {
                                field: 'num',
                                title: '库存数量',
                                align:'center',
                            } /*, {
	                            field: 'container_name',
	                            title: '容器名称',
	                            align:'center'
	                        },{
	                            field: 'is_devanning',
	                            title: '是否拆箱',
	                            align:'center'
	                            ,templet: function(d){
	                                var value = d.is_devanning;
	                                if(value == '0'){
	                                    return "是";
	                                } else if (value == '1') {
	                                    return "否";
	                                }
	                            }
	                        }, {
                            field: 'barcode_type',
                            title: '条码类型',
                            align:'center'
                            ,templet: function(d){
                                var value = d.barcode_type;
                                if(value == '0'){
                                    return "系统码";
                                } else if (value == '1') {
                                    return "客户码1";
                                } else if (value == '2') {
                                    return "客户码2";
                                } else {
                                    return "无码";
                                }
                                return value;
                            }
                        }*/
                            ]
                        ]
                        ,page: true
                    });
                    
                    /* **********键盘Enter事件*********** */ 
                    $(document).keydown(function (event) {
                        if (event.keyCode == 13) { //绑定回车 
                        	var materiel_name=$('#materiel_name').val();
                     		var materiel_num=$('#materiel_num').val();
                     		var table = layui.table;
                     		var verify = /^[0-9,-]*$/;
                    		//if(verify.test(materiel_num)){
                    			var split = materiel_num.split(',')
                    			if(split.length <= 5){
                    				table.reload('andProcut3Id',{
                						method:'post'
                						,where:{"materielName":materiel_name,"materielNum":materiel_num}
                		         		,page: {
                		                    curr: 1//重新从第 1 页开始
                		                }
                					});
                    			}else{
                    				layer.msg("最多可同时查5个！");
                    			}
                    		/*} else{
                    			layer.msg("只能输入数字和英文逗号！");
                    		} */
            	    		return false;
            	        }
                    });
                  	/* **********Enter事件*********** */
                }
            });
		}
    }

    //获取当前时间
    function curentTime() {
		var now=new Date();
        var year=now.getFullYear(); 
  	    var month=now.getMonth()+1; 
  	    var date=now.getDate(); 
  	    var hour=now.getHours(); 
  	    var minute=now.getMinutes(); 
  	    var second=now.getSeconds(); 
  	   	if (month >= 1 && month <= 9) {
  	    	month = "0" + month;
  	    }
  	    if (date >= 0 && date <= 9) {
  	       	date = "0" + date;
  	    } 
  	   	if (hour >= 1 && hour <= 9) {
  		  	hour = "0" + hour;
  	    }
  	  	if (minute >= 1 && minute <= 9) {
  			minute = "0" + minute;
  	    }
  	 	if (second >= 1 && second <= 9) {
  			second = "0" + second;
  	    }
  		var time =year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
        return time;
    }
    
    function add0(m){
        return m<10?'0'+m:m
    }
    
    toastrStyle();
    //获取行索引
    var LayUIDataTable = (function () {
        var rowData = {};
        var $;
        function checkJquery () {
            if (!$) {
                console.log("未获取jquery对象，请检查是否在调用ConvertDataTable方法之前调用SetJqueryObj进行设置！")
                return false;
            } else return true;
        }
        function ConvertDataTable (callback) {
            if (!checkJquery()) return;
            var dataList = [];
            var rowData = {};
            var trArr = $(".layui-table-body.layui-table-main tr");// 行数据
            if (!trArr || trArr.length == 0) {
                console.log("未获取到相关行数据，请检查数据表格是否渲染完毕！");
                return;
            }
            $.each(trArr, function (index, trObj) {
                var currentClickRowIndex;
                var currentClickCellValue;

                $(trObj).click(function (e) {
                    var returnData = {};
                    var currentClickRow = $(e.currentTarget);
                    currentClickRowIndex = currentClickRow.data("index");
                    currentClickCellValue = e.target.innerHTML
                    $.each(dataList[currentClickRowIndex], function (key, obj) {
                        returnData[key] = obj.value;
                    });
                    callback(currentClickRowIndex, currentClickCellValue, returnData);
                });
                var tdArrObj = $(trObj).find('td');
                rowData = {};
                //  每行的单元格数据
                $.each(tdArrObj, function (index_1, tdObj) {
                    var td_field = $(tdObj).data("field");
                    rowData[td_field] = {};
                    rowData[td_field]["value"] = $($(tdObj).html()).html();
                    rowData[td_field]["cell"] = $(tdObj);
                    rowData[td_field]["row"] = $(trObj);

                })
                dataList.push(rowData);
            })
            return dataList;
        }

        return {
            SetJqueryObj: function (jqueryObj) {
                $ = jqueryObj;
            }
            , ParseDataTable: ConvertDataTable
            , HideField: function (fieldName) {
                if (!checkJquery()) return;
                if (fieldName instanceof Array) {
                    $.each(fieldName, function (index, field) {
                        $("[data-field='" + field + "']").css('display', 'none');
                    })
                } else if (typeof fieldName === 'string') {
                    $("[data-field='" + fieldName + "']").css('display', 'none');
                } else {

                }
            }
        }
    })();
</script>
</body>
</html>